
// pages/chat/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    chatHistory: [],
    inputText: '',
    scrollTop: 0, // 控制上滑距离  
    windowHeight: 0, // 页面高度  
  },
  onInputChange: function (e) {
    let val = e.detail.value
    if (val.length >= 30) {
      this.setData({
        textarea: true
      })
    } else {
      this.setData({
        textarea: false
      })
    }
    this.setData({
      inputText: val,
      length: val.length
    });
  },
  /**
   * 将推荐的提问值 复制到 input中
   * 然后调用sendMessage 方法(略)
   * @param {*} params 
   */
  CatchInputValue: function (params) {
    const quevalue = params.currentTarget.dataset.quevalue
    this.setData({
      inputText: quevalue
    })
    // this.sendMessage()
  },
  /**
   * 点击复制
   */
  bindCopyTap(params) {
    const copyText = params.currentTarget.dataset.copytext
    // console.log(copyText)
    wx.setClipboardData({ data: copyText })
  },
  /**
 * 点击编辑editText
 */
  bindEditTap(params) {
    const editText = params.currentTarget.dataset.edittext
    this.setData({
      inputText: editText
    })
    if (editText.length >= 30) {
      this.setData({
        textarea:  true
      })
    }
  },
  sendMessage: function () {
    if (this.data.inputText.length > 800) {
      wx.showToast({ icon: "error", title: "问题字数达最大限度800字" })
    }
    if (this.data.inputText.trim() !== '') {
      // 添加到聊天历史  
      wx.showLoading({
        title: '让我想想...',
      })
      const newMessage = {
        sender: 'user',
        text: this.data.inputText
      };
      let chatHistory = this.data.chatHistory;
      chatHistory.push(newMessage);
      // 发送消息到后端，并AI回复  
      this.getAIResponse(this.data.inputText).then(response => {
        let towxml = app.towxml(response, 'markdown');
        const aiMessage = {
          sender: 'bot',
          text: response,
          towxml: towxml
        };
        chatHistory.push(aiMessage);
        wx.hideLoading()
        this.pageScrollToBottom();
        this.setData({
          chatHistory: chatHistory,
          inputText: '',// 清空输入框  
          textarea:false
        });
      });

    }
    this.pageScrollToBottom();
  },
  getAIResponse: function (message) {
    return new Promise(resolve => {
      setTimeout(() => {
        wx.request({
          url: 'http://113.25.182.244:7891/api/ai/chat',
          method: 'POST', 
          data: { 
            id: 2,
            userMessage: message 
          },
          success(res) {
            if (res.data.code === 500) {
              wx.showModal({
                title: '注意',
                content: res.data.msg,
                showCancel: false
              })
            }
            let result = res.data
            resolve(result);
          }
        })
      }, 1000);
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { 

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    var height = wx.getSystemInfoSync().windowHeight;
    this.setData({
      windowHeight: height
    });
    this.pageScrollToBottom();
  },
  /**
   * 自动下滑到页面底部
   */
  pageScrollToBottom: function () {
    var that = this;
    wx.createSelectorQuery().select('#page').boundingClientRect(function (rect) {
      if (rect) {
        that.setData({
          scrollTop: rect.height
        });
      }
    }).exec();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this
    wx.getStorage({
      key: 'chatHistory',
      encrypt: true,
      success(res) {
        let data = res.data
        that.setData({
          chatHistory: JSON.parse(data)
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    let data = this.data.chatHistory
    if (data.length > 0) {
      wx.setStorage({ key: "chatHistory", data: JSON.stringify(data), encrypt: true, })
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("onUnload")
    let data = this.data.chatHistory
    if (data.length > 0) {
      wx.setStorage({ key: "chatHistory", data: JSON.stringify(data), encrypt: true, })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})